import 'dart:convert';

import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:library_base/base/base_app_state_page.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/entities/device_entity.dart';
import 'package:library_base/ext/list_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/utils/channel.dart';
import 'package:library_base/widget/dialog/dialog_util.dart';
import 'package:library_base/widget/image/local_image.dart';
import 'package:library_base/widget/multi_state_widget/multi_controller.dart';
import 'package:library_base/widget/multi_state_widget/multi_state_widget.dart';
import 'package:module_wms/page/outbound_orders/as_order/order_detail/print_detail/search_device/search_device_controller.dart';
import 'package:module_wms/page/outbound_orders/as_order/order_detail/print_detail/search_device/search_device_page_ui.dart';

class SearchDevicePage extends StatefulWidget {
  const SearchDevicePage({Key? key}) : super(key: key);

  @override
  _SearchDevicePageState createState() => _SearchDevicePageState();
}

class _SearchDevicePageState extends BaseState<SearchDevicePage, SearchDeviceController> {

  final MultiController multiController = MultiController();

  MethodChannel fromAndroidChannel = const MethodChannel("SearchDevicePageFlutter");

  List<DeviceEntity> deviceEntities = [];

  @override
  void onCreate() {
    setTitle(MultiLanguage.add_printer.tr);
    setRightText('设备搜索中...');
    multiController.initStatus = MultiStateStatus.loading;
    fromAndroidChannel.setMethodCallHandler(flutterMethod);
    sendAndroidChannel.invokeMethod(SEARCH_DEVICE);
  }

  @override
  void onAppBarRightClick(){
    if(multiController.initStatus == MultiStateStatus.content || multiController.initStatus == MultiStateStatus.empty){
      sendAndroidChannel.invokeMethod(SEARCH_DEVICE);
    }
  }

  Future<dynamic> flutterMethod(MethodCall methodCall) async{
    switch (methodCall.method) {
      ///设备搜索中
      case SEARCHING_CHANNEL:
        setRightText('设备搜索中...');
        deviceEntities.clear();
        multiController.initStatus = MultiStateStatus.loading;
        break;

      case DEVICE_NOT_FOUND_CHANNEL:
        setRightText('重新搜索');
        multiController.initStatus = MultiStateStatus.empty;
        break;

      case ADD_DEVICE_LIST:
        var device = DeviceEntity.fromJson(json.decode(methodCall.arguments) as Map<String, dynamic>);
        var isIn = deviceEntities.where((element) => device.device.address == element.device.address).toList();
        if(isIn.isEmpty){
          deviceEntities.add(device);
        }
        break;

      case SHOW_DEVICE_LIST:
        setRightText('重新搜索');
        multiController.initStatus = MultiStateStatus.content;
        break;

        ///连接弹窗关闭
      case DISS_CONNECT_DIALOG:
        Get.back();
        break;

        ///连接蓝牙成功
      case CONNECT_SUCCESS:
        DeviceEntity.fromJson(json.decode(methodCall.arguments) as Map<String, dynamic>);
        Get.back();
        break;

        ///蓝牙连接失败，显示弹窗原因
      case CONNECT_FAIL:
        var device = DeviceEntity.fromJson(json.decode(methodCall.arguments) as Map<String, dynamic>);
        DialogUtil.showCupertinoAlertDialog(context,
            title: "重新连接",
            content: "无法与${device.getName()}连接,可能原因如下:\n1.该设备蓝牙关闭,或不在通信范围内(10米);2.该设备已经与其他设备连接,请断开后重试",
            cancel: MultiLanguage.cancel.tr,
            confirm: MultiLanguage.determine.tr,
            cancelPressed: () => Get.back(),
            confirmPressed: (){
              Get.back();
              connect(device);
            });
        break;
    }
    if(mounted){
      setState(() {});
    }
  }

  @override
  SearchDeviceController registerController() => Get.find<SearchDeviceController>();

  @override
  List<Widget> getMainChildrenWidget(BuildContext context) {
    return [
      Expanded(
        child: Container(
          color: Colors.white,
          child: Column(
            children: [
              Expanded(
                child: MultiStateWidget(
                  loadingWidget: Container(
                      alignment: Alignment.center,
                      child:Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        LocalImage("common_searching",package: Constant.packLib(),width: 200.w,height: 227.w),
                        gapH18,
                        Row(mainAxisSize: MainAxisSize.min,
                          children: [
                            Text(MultiLanguage.searching_printer.tr,style: normalTextColor28),
                            AnimatedTextKit(
                              animatedTexts: [
                                WavyAnimatedText('......',textStyle: normalTextColor28),
                              ],
                              isRepeatingAnimation: true,
                              repeatForever: true,
                            ),
                          ],
                        ),
                      ],
                  )),
                  emptyWidget: Container(
                      alignment: Alignment.center,
                      child:Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          LocalImage("common_search_noting",package: Constant.packLib(),width: 200.w,height: 227.w),
                          gapH18,
                          Row(mainAxisSize: MainAxisSize.min,
                            children: [
                              Text(MultiLanguage.printer_not_found.tr,style: normalTextColor28),
                            ],
                          ),
                        ],
                      )),
                  controller: multiController,
                  buildChild: (){
                    return Column(
                      children: buildDeviceItem(),
                    );
                  },
                  child: null,
                ),
              )
            ],
          ),
        ),
      ),
    ];
  }

  List<Widget> buildDeviceItem(){
    return deviceEntities.buildItem((index, element) {
      return buildItem(element,connect:connect);
    }, dividingLine: () {
      return gapH18;
    });
  }

  void connect(DeviceEntity element){
    DialogUtil.showLoadingCenterDialog(context,content: '蓝牙连接中...');
    sendAndroidChannel.invokeMethod(CONNECT_DEVICE,element.device.address);
  }

  @override
  void onDestroy() {
    super.onDestroy();
    sendAndroidChannel.invokeMethod(STOP_SEARCH_DEVICE);
  }

}
